package cn.hsp.harmonyosdemos.slice;

import cn.hsp.harmonyosdemos.OrmDBDemo;
import cn.hsp.harmonyosdemos.OrmUser;
import cn.hsp.harmonyosdemos.ResourceTable;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.window.dialog.ToastDialog;
import ohos.data.DatabaseHelper;
import ohos.data.orm.OrmContext;
import ohos.data.orm.OrmPredicates;

import java.util.List;

/**
 * 厦门大学计算机专业 | 前华为工程师
 * 专注《零基础学编程系列》https://cxyxy.blog.csdn.net/article/details/121134634
 * 包含：Java | 安卓 | 前端 | Flutter | iOS | 小程序 | 鸿蒙
 * 公众号：花生皮编程
 */
public class MainAbilitySlice extends AbilitySlice {
    private OrmContext ormContext;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);

        findComponentById(ResourceTable.Id_writeText).setClickedListener(component -> write());
        findComponentById(ResourceTable.Id_readText).setClickedListener(component -> read());
        findComponentById(ResourceTable.Id_modifyText).setClickedListener(component -> modify());
        findComponentById(ResourceTable.Id_delText).setClickedListener(component -> del());

        initDb();
    }

    private void initDb() {
        DatabaseHelper databaseHelper = new DatabaseHelper(this);
        ormContext = databaseHelper.getOrmContext("OrmDBTest", "OrmDBTest.db", OrmDBDemo.class);
    }

    private void write() {
        int userId = 1;
        OrmUser ormUser = new OrmUser();
        ormUser.setUserId(userId);
        ormUser.setUserName("花生皮编程");
        ormContext.insert(ormUser);
        ormContext.flush();
    }

    private void read() {
        List<OrmUser> ormUsers = query();
        new ToastDialog(getContext()).setText(ormUsers.get(0).getUserName()).show();
    }

    private List<OrmUser> query() {
        //查询userId = 1的数据
        int userId = 1;
        OrmPredicates ormPredicates = ormContext.where(OrmUser.class).equalTo("userId", userId);
        return ormContext.query(ormPredicates);
    }

    private void modify() {
        //将查询出来的数据值修改后更新到数据库
        OrmUser ormUser = query().get(0);
        if (ormUser == null) {
            return;
        }
        ormUser.setUserName("花生皮編程2");
        ormContext.update(ormUser);
        ormContext.flush();
    }

    private void del() {
        //将查询出来的第一条数据从数据库中删除
        OrmUser ormUser = query().get(0);
        if (ormUser == null) {
            return;
        }
        ormContext.delete(ormUser);
        ormContext.flush();
    }
}
